package logic

import (
	"context"
	"fmt"
	"lucky_srv/cache"
	"strconv"

	"lucky_srv/internal/svc"
	"lucky_srv/lucky"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartListLogic {
	return &CartListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartListLogic) CartList(in *lucky.CartListRequest) (*lucky.CartListResponse, error) {
	// todo: add your logic here and delete this line

	var total float64
	var listCart []*lucky.CartList
	key := fmt.Sprintf("cart_%d_*", in.UserId)
	keys := cache.Rdb.Keys(context.Background(), key).Val()

	if len(keys) == 0 {
		return &lucky.CartListResponse{}, nil
	}

	for _, s := range keys {
		goodsMap, _ := cache.Rdb.HGetAll(context.Background(), s).Result()

		goodsId, _ := strconv.Atoi(goodsMap["goods_id"])
		goodsPrice, _ := strconv.ParseFloat(goodsMap["goods_price"], 64)
		num, _ := strconv.Atoi(goodsMap["num"])
		total += goodsPrice * float64(num)

		listCart = append(listCart, &lucky.CartList{
			UserId:  in.UserId,
			GoodsId: int64(goodsId),
			Title:   goodsMap["goods_title"],
			Price:   float32(goodsPrice),
			Num:     int64(num),
		})
	}

	return &lucky.CartListResponse{
		List: listCart,
	}, nil
}
